class_name Dialog
extends Area2D

@export var text: String = "Placeholder text"
@export var duration: float = 5
@export var wait_time: float = 2.0
var show_dialog: bool = false
var label_base_pos: Vector2
var index: int = -1
var speed: float = 0

var disabled := false:
	set(v):
		monitoring = !v

@onready var label: Label = $CanvasLayer/Label
@onready var timer: Timer = $Timer


func _ready() -> void:
	label.text = text
	label_base_pos = label.global_position


func _process(delta: float) -> void:
	index = GlobalGameData.dialog_showing_list.find(self.name)
	
	if show_dialog or timer.time_left > 0:
		label.modulate.a = move_toward(label.modulate.a, 1.0, duration * delta)
	else:
		label.modulate.a = move_toward(label.modulate.a, 0.0, duration * delta)
		if self.name in GlobalGameData.dialog_showing_list:
			GlobalGameData.dialog_showing_list.erase(self.name)
			
	# 莫名其妙写了一个弹簧的效果
	#speed = move_toward(speed, (label_base_pos.y - index * 45) - label.position.y , 100 * delta)
	speed = move_toward(speed, ((label_base_pos.y - index * 64) - label.global_position.y) * 0.1, 100 * delta)
	label.global_position.y += speed


func _on_body_entered(_body: Node2D) -> void:
	show_dialog = true
	if self.name not in GlobalGameData.dialog_showing_list:
		GlobalGameData.dialog_showing_list.append(self.name)


func _on_body_exited(_body: Node2D) -> void:
	show_dialog = false
	timer.wait_time = wait_time
	timer.start()
